//
//  BVPublishedViewController.m
//  XiangYu
//
//  Created by YYKJ on 2017/6/6.
//  Copyright © 2017年 YYKJ. All rights reserved.
//

#import "BVPublishedViewController.h"
#import "BVTextView.h"
#import "BVAMPSearchPOIManager.h"

#import "HXPhotoViewController.h"
#import "HXPhotoView.h"

@interface BVPublishedViewController ()<UITableViewDelegate ,UITableViewDataSource,HXPhotoViewDelegate>

@property (strong, nonatomic) HXPhotoManager *manager;
@property (strong, nonatomic) HXPhotoView *photoView;

@property (nonatomic ,strong) BVTextView            *contentTextV;
@property (nonatomic ,strong) BVAMPSearchPOIManager *searchManager;
@property (nonatomic ,strong) UITableView           *tableView;
@property (nonatomic ,strong) NSMutableArray        *dataArr;
@property (nonatomic ,strong) UIButton              *locationBtn;

@end

@implementation BVPublishedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor BVBackgroundLightGrayColor]];
    [self.navigationItem setTitle:@"发表动态"];
    
    [self setNav];
    [self layoutUI];
    [self layouTwoUI];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
    
}

-(void)setNav{
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setFrame:CGRectMake(0, 10, 40, 28)];
    [rightBtn setTitle:@"发表" forState:UIControlStateNormal];
    [rightBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [rightBtn.titleLabel setTextAlignment:NSTextAlignmentRight];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    [self.navigationItem setRightBarButtonItem:rightBarBtn];
    
}

-(void)layoutUI{
    
    UIView *bgView = [[UIView alloc]init];
    [self.view addSubview:bgView];
    [bgView setBackgroundColor:[UIColor whiteColor]];
    [bgView setFrame:CGRectMake(10, 20, ScreenW-20, 190)];
    [bgView.layer setBorderColor:[[UIColor BVLineGrayColor] CGColor]];
    [bgView.layer setBorderWidth:1.0];
    [bgView.layer setMasksToBounds:YES];
    [bgView.layer setCornerRadius:5.0];
    
    self.contentTextV = [[BVTextView alloc] init];
    [bgView addSubview:self.contentTextV];
    self.contentTextV.placeholder = @" 您想说点什么...";
    self.contentTextV.placeholderColor = [UIColor BVTextGrayColor];
    self.contentTextV.frame = CGRectMake(0, 0, ScreenW-20, 150);
    self.contentTextV.textColor = [UIColor BVTextGrayColor];;
    
    self.locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bgView addSubview:self.locationBtn];
    [self.locationBtn setBackgroundColor:[UIColor whiteColor]];
    [self.locationBtn setTitle:@"所在位置" forState:UIControlStateNormal];
    [self.locationBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [self.locationBtn setTitleColor:[UIColor BVTextGrayColor] forState:UIControlStateNormal];
    [self.locationBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [self.locationBtn setImage:[UIImage imageNamed:@"dizhi"] forState:UIControlStateNormal];
    [self.locationBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [self.locationBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
    [self.locationBtn addTarget:self action:@selector(positionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.locationBtn.sd_layout
    .topSpaceToView(self.contentTextV, 0)
    .leftEqualToView(self.contentTextV)
    .rightEqualToView(self.contentTextV)
    .bottomSpaceToView(bgView, 0);
    
    [self.view addSubview:self.tableView];
}

-(void)positionBtnClick:(UIButton *)btn{
    [self.view endEditing:YES];
    [_photoView setHidden:YES];
    [self.tableView setHidden:NO];
    
     [self.hud show:YES];
     __weak __typeof(self) weakSelf = self;;
    self.searchManager = [[BVAMPSearchPOIManager alloc]initSearchPOI];
    
    self.searchManager.searchPOIBlock = ^(NSMutableArray *arr) {
        [weakSelf.dataArr removeAllObjects];
        [weakSelf.dataArr addObjectsFromArray:arr];
        [weakSelf.tableView reloadData];
        [weakSelf.hud hide:YES];
    };
    self.searchManager.searchFailure = ^(NSString *str) {
        [weakSelf.hud hide:YES];
        [weakSelf showError:str];
        [weakSelf.photoView setHidden:NO];
    };
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * ID = @"ContactCell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    
        UILabel * lb = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 300, 40)];
        [cell.contentView addSubview:lb];
        [lb setTextColor:[UIColor BVTextGrayColor]];
        [lb setFont:[UIFont systemFontOfSize:16]];
        lb.tag = 200;
    }
    [cell setBackgroundColor:[UIColor clearColor]];
    
    UILabel *lb = (UILabel *)[cell.contentView viewWithTag:200];
    [lb setText:[NSString stringWithFormat:@"%@",self.dataArr[indexPath.row]]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.locationBtn setTitle:[NSString stringWithFormat:@"%@",self.dataArr[indexPath.row]] forState:UIControlStateNormal];
    [self.tableView setHidden:YES];
    [_photoView setHidden:NO];
}

-(UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 230, ScreenW-20, ScreenH-64-240) style:UITableViewStylePlain];
        [self.tableView setDelegate:self];
        [self.tableView setDataSource:self];
        [self.tableView setBackgroundColor:[UIColor clearColor]];
        [self.tableView setTableFooterView:[UIView new]];
        [self.tableView setShowsVerticalScrollIndicator:NO];
        [self.tableView setRowHeight:50];
    }
    return _tableView;
}

-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

#pragma mark - 关于图片选择
-(void)layouTwoUI{
    
    _photoView = [HXPhotoView photoManager:self.manager];
    [self.view addSubview:_photoView];
    _photoView.frame = CGRectMake(12, 220, ScreenW - 24, 0);
    _photoView.delegate = self;
    self.photoView = _photoView;
}

- (HXPhotoManager *)manager
{
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhotoAndVideo];
        _manager.openCamera = YES;
        _manager.outerCamera = YES;
        _manager.showFullScreenCamera = YES;
        _manager.photoMaxNum = 4;
        _manager.videoMaxNum = 4;
        _manager.maxNum = 8;
    }
    return _manager;
}

- (void)didNavBtnClick {
    [self.photoView goPhotoViewController];
}

- (void)photoView:(HXPhotoView *)photoView changeComplete:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photos videos:(NSArray<HXPhotoModel *> *)videos original:(BOOL)isOriginal {
    NSSLog(@"所有:%ld - 照片:%ld - 视频:%ld",(unsigned long)allList.count,(unsigned long)photos.count,(unsigned long)videos.count);
    [HXPhotoTools getImageForSelectedPhoto:photos type:HXPhotoToolsFetchHDImageType completion:^(NSArray<UIImage *> *images) {
        NSSLog(@"啊哈 %@",images);
        for (UIImage *image in images) {
            if (image.images.count > 0) {
                // 到这里了说明这个image  是个gif图
            }
        }
    }];
    
}
- (void)photoView:(HXPhotoView *)photoView deleteNetworkPhoto:(NSString *)networkPhotoUrl {
    
    NSSLog(@"%@",networkPhotoUrl);
}
- (void)photoView:(HXPhotoView *)photoView updateFrame:(CGRect)frame {
    NSSLog(@"%@",NSStringFromCGRect(frame));
}

// 压缩视频并写入沙盒文件
- (void)compressedVideoWithURL:(id)url success:(void(^)(NSString *fileName))success failure:(void(^)())failure
{
    AVURLAsset *avAsset;
    if ([url isKindOfClass:[NSURL class]]) {
        avAsset = [AVURLAsset assetWithURL:url];
    }else if ([url isKindOfClass:[AVAsset class]]) {
        avAsset = (AVURLAsset *)url;
    }
    
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
        
        NSString *fileName = @""; // 这里是自己定义的文件路径
        
        NSDate *nowDate = [NSDate date];
        NSString *dateStr = [NSString stringWithFormat:@"%ld", (long)[nowDate timeIntervalSince1970]];
        
        NSString *numStr = [NSString stringWithFormat:@"%d",arc4random()%10000];
        fileName = [fileName stringByAppendingString:dateStr];
        fileName = [fileName stringByAppendingString:numStr];
        
        // ````` 这里取的是时间加上一些随机数  保证每次写入文件的路径不一样
        fileName = [fileName stringByAppendingString:@".mp4"]; // 视频后缀
        NSString *fileName1 = [NSTemporaryDirectory() stringByAppendingString:fileName]; //文件名称
        exportSession.outputURL = [NSURL fileURLWithPath:fileName1];
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.shouldOptimizeForNetworkUse = YES;
        
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            
            switch (exportSession.status) {
                case AVAssetExportSessionStatusCancelled:
                    break;
                case AVAssetExportSessionStatusCompleted:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (success) {
                            success(fileName1);
                        }
                    });
                }
                    break;
                case AVAssetExportSessionStatusExporting:
                    break;
                case AVAssetExportSessionStatusFailed:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (failure) {
                            failure();
                        }
                    });
                }
                    break;
                case AVAssetExportSessionStatusUnknown:
                    break;
                case AVAssetExportSessionStatusWaiting:
                    break;
                default:
                    break;
            }
        }];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
